package com.alibaba.citrus.ots.unified.inventory.facade.service;

import com.alibaba.citrus.common.util.Lists;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.log.ModuleEnum;
import com.alibaba.citrus.ots.common.util.NameUtil;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderDetailReadRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderReadRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.EsAllocateApplyOrderIndexRepository;
import com.alibaba.citrus.ots.unified.inventory.utils.AllocateApplyOrdeUtils;
import com.alibaba.citrus.ots.unified.inventory.utils.EnumUtils;
import com.alibaba.citrus.ots.unified.inventory.utils.InfoUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.log.model.OpLogDateTypeEnum;
import com.alibaba.cz.base.tool.log.model.OperatorType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationById2Request;
import com.epoch.app.bcots.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.model.dto.RoleSDO;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.otsplatformenhance.model.dto.OperateLogDiff;
import com.epoch.app.otsplatformenhance.model.dto.OperateQueryInfoRequest;
import com.epoch.app.otsplatformenhance.queryoperatelog.service.QueryOperateLogService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.dto.GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.otsunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.otsunifiedinventory.contants.OtsUnifiedInventoryConstants;
import com.epoch.app.otsunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderGoodsDetailDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderListDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderRelationDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderResponse;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderQueryResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderCodeQueryRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderDocumentLogDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderQueryRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateOrderScItemDetail;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateOrganizationSelect;
import com.epoch.app.otsunifiedinventory.model.dto.QueryDocumentLogReques;
import com.epoch.app.otsunifiedinventory.model.enums.AllocateApplyOrderOperationTypeEnum;
import com.epoch.app.otsunifiedinventory.sdo.AllocateApplyOrderSDO;
import com.epoch.app.otsunifiedinventory.sdo.enums.AllocateApplyOrderStatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Primary
public class AllocateApplyOrderReadServiceImpl implements AllocateApplyOrderReadService {
    Log log = Log.getLogger(AllocateApplyOrderReadServiceImpl.class);
    /**
     * 分子公司
     */
    private static final Integer COMPANY = 103;
    /**
     * 销售组织
     */
    private static final Integer SALES_ORGANIZATION = 104;
    /**
     * 待我处理状态
     */
    private static final Integer PROCESSING = 10;
    /**
     * 全部状态
     */
    private static final Integer ALL_STATUS = 99;

    private static final String COMMA = ",";
    /**
     * 冒号
     */
    private static final String COLON = "：";
    /**
     * 右箭头
     */
    private static final String RIGHT_ARROW = " ——> ";
    /**
     * 空字符串
     */
    private static final String NULL_STRING = "";
    /**
     * 字符串 3
     */
    private static final String THREE_STRING = "3";
    /**
     * 字符串 0
     */
    private static final String ZERO_STRING = "0";
    /**
     *  0
     */
    private static final int ZERO = 0;
    /**
     *  10
     */
    private static final int TEN = 10;
    private static final int THOUSAND = 1000;
    private static final String CODE = "code";
    private static final String STATUS = "status";
    private static final String ALLOCATE_APPLY_ORDER_DETAIL = "allocateApplyOrderDetail";
    //分子公司业务员
    private static final String SALES_MAN_ROLE_CODE = "001";

    @Resource
    private AllocateApplyOrderReadRepository allocateApplyOrderReadRepository;

    @Resource
    private AllocateApplyOrderDetailReadRepository allocateApplyOrderDetailReadRepository;

    @Resource
    private EsAllocateApplyOrderIndexRepository esAllocateApplyOrderIndexRepository;
    @Resource
    @Qualifier("allocateOrderReadServiceImpl")
    private AllocateOrderReadService allocateOrderReadService;

    @Resource
    private QueryOperateLogService queryOperateLogService;

    @Resource
    private BaseDataService baseDataService;

    @Override
    @FacadeInvoker(value = "预报单列表查询", errorCode = "OTS-03-001-00-15-046")
    public Result<List<AllocateApplyOrderListDTO>> queryAllocateApplyOrderList(AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest) {
        log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.request:{}",JSONObject.toJSONString(allocateApplyOrderQueryRequest));
        /**
         * 权限数据过滤
         * 先判断当前人角色，调度员、总经理、副总 可以查看 其他角色返回为空
         * 在判断如果是销售组织以上可以查找、销售大区以上所有都回复，其他值返回为空
         * organizationList 组 分公司
         * bizUnitList 单元 销售组织
         */
        Result<List<AllocateApplyOrderListDTO>> listResult = new Result<>();
        List<AllocateApplyOrderListDTO> list = new ArrayList<>();
        listResult.setResult(list);
        listResult.setSuccess(true);
        boolean isQuery = false;
        boolean isHeadquarters = false;
        //获取可查看的角色，将可查看的角色放map中，为后续判断做处理用
        String allocateApplyOrderRolesThatCanBeViewed = OtsUnifiedInventoryConstants.ALLOCATE_APPLY_ORDER_ROLES_THATCAN_BE_VIEWED();
        List<String> allocateApplyOrderRolesThatCanBeVieweds = Arrays.asList(allocateApplyOrderRolesThatCanBeViewed.split(COMMA));
        Map<String, String> allocateApplyOrderRolesThatCanBeViewedMap = new HashMap<>();
        for (String s : allocateApplyOrderRolesThatCanBeVieweds) {
            allocateApplyOrderRolesThatCanBeViewedMap.put(s, s);
        }
        //获取当前登录人的角色和组织判断查看权限
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        log.info("AllocateApplyOrderReadServiceImpl.getLoginEmployeeInfo.result:{}",JSONObject.toJSONString(loginEmployeeInfo));
        if (Objects.nonNull(loginEmployeeInfo) && CollectionUtils.isNotEmpty(loginEmployeeInfo.getRoles())) {
            //2022.0223 新增业务员 可以查看调拨预报单的总部销售 工厂直发
            boolean isSalesMan = false;
            //循环角色信息，查看角色中在可查看map中是否有值，有值标记可以查看
            for (RoleSDO roleSDO : loginEmployeeInfo.getRoles()) {
                String code = allocateApplyOrderRolesThatCanBeViewedMap.get(roleSDO.getCode());
                if (StringUtils.isNotEmpty(code)) {
                    isQuery = true;
                }
                //如果是业务员
                if (SALES_MAN_ROLE_CODE.equals(roleSDO.getCode())){
                    isSalesMan = true;
                }
            }
            if (Objects.nonNull(loginEmployeeInfo) && Objects.nonNull(loginEmployeeInfo.getOrganizationSDO())) {
                Integer type = loginEmployeeInfo.getOrganizationSDO().getType();
                /**
                 * GROUP(100, "蒙牛集团"),
                 *     ENTERPRISE_GROUP(101, "事业部"),
                 *     REGION(102, "销售大区"),
                 *     COMPANY(103, "分子公司"),
                 *
                 *     SALES_ORGANIZATION(104, "销售组织"),
                 *     SALES_CHANNEL(105, "销售渠道"),
                 *     SALES_DEPARTMENT(106, "销售部门");
                 *     判断组织，大于104的组织不可查看
                 *     小于103的可以查看全部
                 *     等于103或104的只可以查看相关数据
                 */
                if (Objects.isNull(type) || type > SALES_ORGANIZATION) {
                    isQuery = false;
                } else {
                    if (COMPANY.equals(type)) {
                        allocateApplyOrderQueryRequest.setBizUnitList(loginEmployeeInfo.getOrganizationSDO().getId());
                    }
                    if (SALES_ORGANIZATION.equals(type)) {
                        allocateApplyOrderQueryRequest.setOrganizationList(loginEmployeeInfo.getOrganizationSDO().getId());
                    }
                    if (type < COMPANY){
                        isHeadquarters = true;
                    }
                }
                // 业务员特殊判断 能看到该分公司下 总部销售的工厂直发的
                if (isSalesMan){
                    //如果选择否 那么返回空结果
                    if (Objects.equals(allocateApplyOrderQueryRequest.getIsDTC(),Boolean.FALSE)){
                        return listResult;
                    }
                    allocateApplyOrderQueryRequest.setIsDTC(true);
                    OrganizationSDO organizationSDO = loginEmployeeInfo.getOrganizationSDO();
                    //循环找到对应的分子公司层级 type是103 根据父组织id寻找.
                    while (!Objects.equals(103,organizationSDO.getType())){
                        BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
                        if (org.apache.commons.lang3.StringUtils.isBlank(organizationSDO.getParentId())){
                            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDO));
                            break;
                        }
                        request.setId(organizationSDO.getParentId());
                        Result<OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
                        if (organizationSDOResult == null|| organizationSDOResult.getResult() == null){
                            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                        organizationSDO = organizationSDOResult.getResult();
                        if (organizationSDO.getType() != null && organizationSDO.getType() < 103){
                            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.salesMan.org.errorResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                    }
                    //如果是分子公司 就把值给填进去 看该分子公司下的
                    if (Objects.equals(103,organizationSDO.getType())){
                        isQuery = true;
                        allocateApplyOrderQueryRequest.setBizUnitList(organizationSDO.getId());
                    }
                }
            }
        }
        //如果是待回复标记，销售组织和子公司的人看 判断状态中是否有带总部审核状态 如果有 给去掉
        boolean isStatus = false;
        List<Integer> statusNew = new ArrayList<>();
        //是否待回复，是待回复进行状态处理
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getAgency()) && allocateApplyOrderQueryRequest.getAgency()) {
            //判断是否子公司以上组织,如果不是进行状态处理，过滤掉总部回复
            List<Integer> statuss = allocateApplyOrderQueryRequest.getLineStatus();
            if (!isHeadquarters) {
                if (CollectionUtils.isNotEmpty(statuss)){
                    for (Integer status : statuss) {
                        if (ALL_STATUS.equals(status)|| PROCESSING.equals(status)) {
                            isStatus = true;
                        }
                        if (AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode().equals(status)||AllocateApplyOrderStatusEnum.PART_ANSWER.getCode().equals(status)||AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode().equals(status)) {
                            statusNew.add(status);
                        }
                    }
                }else{
                    isStatus = true;
                }
                if (isStatus) {
                    ArrayList<Integer> s = new ArrayList<>();
                    s.add(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
                    s.add(AllocateApplyOrderStatusEnum.PART_ANSWER.getCode());
                    s.add(AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode());
                    allocateApplyOrderQueryRequest.setLineStatus(s);
                } else {
                    allocateApplyOrderQueryRequest.setLineStatus(statusNew);
                }
            }else{
                //总部组织筛选条件
                if (CollectionUtils.isNotEmpty(statuss)){
                    for (Integer status : statuss) {
                        if (AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode().equals(status)
                                ||AllocateApplyOrderStatusEnum.PART_ANSWER.getCode().equals(status)
                                ||AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode().equals(status)
                                ||AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode().equals(status)
                                ||ALL_STATUS.equals(status)|| PROCESSING.equals(status)) {
                            statusNew.add(status);
                        }
                    }
                }else {
                    statusNew.add(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
                    statusNew.add(AllocateApplyOrderStatusEnum.PART_ANSWER.getCode());
                    statusNew.add(AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode());
                    statusNew.add(AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode());
                }
                allocateApplyOrderQueryRequest.setLineStatus(statusNew);
            }
            //使用待回复情况下权限字段作区分
            allocateApplyOrderQueryRequest.setBizUnitIdReply(allocateApplyOrderQueryRequest.getBizUnitList());
            allocateApplyOrderQueryRequest.setSaleOrgIdReply(allocateApplyOrderQueryRequest.getOrganizationList());
            allocateApplyOrderQueryRequest.setBizUnitList(null);
            allocateApplyOrderQueryRequest.setOrganizationList(null);
            allocateApplyOrderQueryRequest.setOutAllocateApplyOrderIds(allocateApplyOrderQueryRequest.getOutAllocateApplyOrderIds());
        }
        //es 查数据
        if (isQuery&&CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getLineStatus())) {
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.queryEsAllocateApplyOrderIndexList.request:{}",JSONObject.toJSONString(allocateApplyOrderQueryRequest));
            listResult = esAllocateApplyOrderIndexRepository.queryEsAllocateApplyOrderIndexList(allocateApplyOrderQueryRequest);
        }
        log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderList.result:{}",JSONObject.toJSONString(listResult));
        return listResult;
    }
    @Override
    @FacadeInvoker(value = "预报单详情", errorCode = "OTS-03-001-00-15-047")
    public Result<AllocateApplyOrderDetailDTO> queryAllocateApplyOrderByCode(
            QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest) {
        log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.request:{}",JSONObject.toJSONString(queryAllocateApplyOrderRequest));
        try {
            //查询预调拨单
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.queryAllocateApplyOrderByCode.request:{}",JSONObject.toJSONString(queryAllocateApplyOrderRequest));
            AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest.getCode());
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.queryAllocateApplyOrderByCode.result:{}",JSONObject.toJSONString(queryAllocateApplyOrderRequest));
            if (null == allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO() ||
                    null == allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getId()) {
                return Result.success(null);
            }
            AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO();
            //查询预调拨单详情
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.loadDetailByOrderId.request:{}",JSONObject.toJSONString(allocateApplyOrderDetailDTO));
            List<AllocateApplyOrderGoodsDetailDTO> list = allocateApplyOrderDetailReadRepository.loadDetailByOrderId(allocateApplyOrderDetailDTO.getId());
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.loadDetailByOrderId.result:{}",JSONObject.toJSONString(list));
            allocateApplyOrderDetailDTO.setList(list);

            //创建调拨单对象
            List<AllocateApplyOrderRelationDTO> allocateApplyOrderRelationDTOS = new ArrayList<>();
            //获取调拨单信息
            AllocateApplyOrderCodeQueryRequest allocateApplyOrderCodeQueryRequest = new AllocateApplyOrderCodeQueryRequest();
            allocateApplyOrderCodeQueryRequest.setAllocateApplyOrderCode(queryAllocateApplyOrderRequest.getCode());
            Result<AllocateOrderQueryResponse> allocateOrderQueryResponseResult = allocateOrderReadService.queryByAllocateApplyOrderCode(allocateApplyOrderCodeQueryRequest);
            //判断预报单是否有值，有值进行处理
            if (Objects.nonNull(allocateOrderQueryResponseResult) && Objects.nonNull(allocateOrderQueryResponseResult.getResult())) {
                AllocateOrderQueryResponse allocateOrderQueryResponse = allocateOrderQueryResponseResult.getResult();
                List<AllocateOrderDTO> allocateOrderDTOS = allocateOrderQueryResponse.getAllocateOrderDTOS();
                if (allocateOrderDTOS.size() > ZERO) {
                    for (AllocateOrderDTO allocateOrderDTO : allocateOrderDTOS) {
                        AllocateApplyOrderRelationDTO allocateApplyOrderRelationDTO = new AllocateApplyOrderRelationDTO();
                        List<AllocateOrderScItemDetail> allocateOrderScItemDetails = allocateOrderDTO.getAllocateOrderScItemDetails();
                        //获取明细数量，转换为BigDecimal计算
                        BigDecimal num = BigDecimal.ZERO;
                        for (AllocateOrderScItemDetail allocateOrderScItemDetail : allocateOrderScItemDetails) {
                            BigDecimal add = new BigDecimal(null == allocateOrderScItemDetail.getQuantity() ? ZERO_STRING : allocateOrderScItemDetail.getQuantity().trim());
                            num = num.add(add);
                        }
                        allocateApplyOrderRelationDTO.setTotalQuantity(num.intValue());
                        allocateApplyOrderRelationDTO.setStatus(InfoUtil.getStatusDesc(allocateOrderDTO.getStatus()));
//                        allocateApplyOrderRelationDTO.setStatus(
//                                EnumUtils.getAllocateStatusEnum(allocateOrderDTO.getStatus()));
                        //创建人名称
                        if (Objects.nonNull(allocateOrderDTO.getCreator())) {
                            JSONObject obj = JSON.parseObject(allocateOrderDTO.getCreator());
                            allocateApplyOrderRelationDTO.setCreator(NameUtil.getRealName(allocateOrderDTO.getCreator()));
//                            allocateApplyOrderRelationDTO.setCreator(obj.getString("realName"));
                        }
                        allocateApplyOrderRelationDTO.setCreateTime(allocateOrderDTO.getGmt_create());
                        allocateApplyOrderRelationDTO.setDeliverTime(allocateOrderQueryResponse.getAllocateOrderDTOS().get(ZERO).getShippingTime());
                        allocateApplyOrderRelationDTO.setAllocateOrderNo(allocateOrderDTO.getCode());
                        allocateApplyOrderRelationDTOS.add(allocateApplyOrderRelationDTO);
                    }
                }
            }
            allocateApplyOrderDetailDTO.setRelationList(allocateApplyOrderRelationDTOS);
            //优化返回数据
            allocateApplyOrderDetailDTO = AllocateApplyOrdeUtils.optimizationAllocateApplyOrderDetail(allocateApplyOrderDetailDTO);
            log.info("AllocateApplyOrderReadServiceImpl.queryAllocateApplyOrderByCode.result:{}",JSONObject.toJSONString(allocateApplyOrderDetailDTO));
            return Result.success(allocateApplyOrderDetailDTO);
        } catch (Exception e) {
            log.error("queryAllocateApplyOrderByCode error!", e);
            return Result.fail("500", e.getMessage());
        }
    }

    @Override
    public Result<AllocateApplyOrderSDO> query(AllocateApplyOrderCodeQueryRequest request) {
        System.out.println();
        return null;
    }

    @Override
    public Result<List<AllocateApplyOrderDocumentLogDTO>> getDocumentLog(QueryDocumentLogReques queryDocumentLogReques) {
        OperateQueryInfoRequest operateQueryInfoRequest = new OperateQueryInfoRequest();
        AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(queryDocumentLogReques.getAllocateApplyOrderCode());
        //操作者类型
        operateQueryInfoRequest.setOperatorType(OperatorType.USER.getOperatorType());
        //模块ID 1: 主数据  2:月度计划 3：调拨一盘货 4：预报销售 5：价格  6：活动
        operateQueryInfoRequest.setModuleId(THREE_STRING);
        //模块名称 必传
        operateQueryInfoRequest.setModuleName(ModuleEnum.UNIFIED_INVENTORY.getModuleName());
        //对象名称 查询字段和查询对象二选一
        operateQueryInfoRequest.setObjectName(queryDocumentLogReques.getAllocateApplyOrderCode());
        //对象ID 如果是对象，填写对象 ID；如果是字段，填写字段的值 前端传
        operateQueryInfoRequest.setObjectId(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getId().toString());
        //数据类型 1：字段类型  2：对象类型
        //使用com.alibaba.cz.base.tool.log.model.OpLogDateTypeEnum中的枚举值
        operateQueryInfoRequest.setDataType(OpLogDateTypeEnum.OBJECT_TYPE.getDataType());
        //是否需要返回新老值
        operateQueryInfoRequest.setNeedReturnNewOldValue(true);
        //起始索引
        operateQueryInfoRequest.setStart(ZERO);
        //页面大小
//        operateQueryInfoRequest.setLimit(TEN);
        operateQueryInfoRequest.setLimit(THOUSAND);
        Result<List<OperateLogDiff>> listResult = queryOperateLogService.queryOperateLogRowDiff(operateQueryInfoRequest);

        List<AllocateApplyOrderDocumentLogDTO> allocateApplyOrderDocumentLogDTOS = new ArrayList<>();
        if (Objects.nonNull(listResult) && Objects.nonNull(listResult.getResult())) {
            List<OperateLogDiff> operateLogList = listResult.getResult();
            for (OperateLogDiff operateLogDiff : operateLogList) {
                AllocateApplyOrderDocumentLogDTO allocateApplyOrderDocumentLogDTO = new AllocateApplyOrderDocumentLogDTO();
                //创建时间
                allocateApplyOrderDocumentLogDTO.setGmtCreate(operateLogDiff.getGmt_create());
                //操作人
                allocateApplyOrderDocumentLogDTO.setOperator(InfoUtil.getRealName(operateLogDiff.getOperatorId()));
                //操作类型
                allocateApplyOrderDocumentLogDTO.setOperationType(EnumUtils.getAllocateApplyOrderOperationTypeEnum(operateLogDiff.getOperateType()));
                String features = operateLogDiff.getFeatures();
                HashMap<String,String> featuresMap = new HashMap();
                if (StringUtils.isNotEmpty(features)){
                    featuresMap = JSONObject.parseObject(features,HashMap.class);
                }
                //操作内容 修改的要展示出来
                List<String> s = new ArrayList<>();
                //创建
                if (AllocateApplyOrderOperationTypeEnum.CREATE.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "创建了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);
                }
                //保存 主单
                if (AllocateApplyOrderOperationTypeEnum.UPDATE.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "更新了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);

//                    allocateApplyOrderDocumentLogDTO.setOperationType("编辑-更新主单字段信息");
//                    String remark = "更新了调拨预报单（"+featuresMap.get(CODE)+"）";
//                    s.add(remark);
//                    List<RowDiff> diffs = operateLogDiff.getRowDiff();
//                    if (CollectionUtils.isNotEmpty(diffs)) {
//                        for (RowDiff rowDiff : diffs) {
//                            //字段名
//                            String label = EnumUtils.getAllocateApplyOrderHeaderEnum(rowDiff.getFieldName());
//                            if (StringUtils.isNotEmpty(label)) {
//                                //旧值
//                                String oldValue = Objects.isNull(rowDiff.getOldValue()) ? NULL_STRING : rowDiff.getOldValue() + RIGHT_ARROW;
//                                //新值
//                                String newValue = rowDiff.getNewValue();
//                                s.add(label + COLON + oldValue + newValue);
//                            }
//                        }
//                    }
                }
                //提交
                if (AllocateApplyOrderOperationTypeEnum.SUBMIT.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    boolean isHeadquartersReply = false;
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                        if (AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode().equals(Integer.valueOf(featuresMap.get(STATUS)))){
                            isHeadquartersReply = true;
                        }
                    }
                    String remark;
                    if (isHeadquartersReply){
                        allocateApplyOrderDocumentLogDTO.setOperationType(AllocateApplyOrderOperationTypeEnum.REPLY.getLabel());
                        remark = "回复了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    }else {
                        remark = "提交了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    }
                    s.add(remark);
                }
                //回复
                if (AllocateApplyOrderOperationTypeEnum.REPLY.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "回复了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);
                }
                //取消
                if (AllocateApplyOrderOperationTypeEnum.CANCEL.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "取消了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);
                }
                //驳回
                if (AllocateApplyOrderOperationTypeEnum.REJECT.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "驳回了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);
                }
                //复制
                if (AllocateApplyOrderOperationTypeEnum.COPY.getValue().equals(operateLogDiff.getOperateType().toString())) {
                    String status = "";
                    if (StringUtils.isNotEmpty(featuresMap.get(STATUS))){
                        status = EnumUtils.getAllocateApplyOrderStatusEnum(Integer.valueOf(featuresMap.get(STATUS)));
                    }
                    String remark = "复制了调拨预报单（"+featuresMap.get(CODE)+"）；状态："+status;
                    s.add(remark);
                }
                allocateApplyOrderDocumentLogDTO.setOperationContent(s);
                allocateApplyOrderDocumentLogDTOS.add(allocateApplyOrderDocumentLogDTO);
                //保存 明细
//                if (AllocateApplyOrderOperationTypeEnum.UPDATE.getValue().equals(operateLogDiff.getOperateType().toString())) {
//                    if (StringUtils.isNotEmpty(featuresMap.get(ALLOCATE_APPLY_ORDER_DETAIL))) {
//                        JSONObject jsonObject = JSON.parseObject(featuresMap.get(ALLOCATE_APPLY_ORDER_DETAIL));
//                        if (Objects.nonNull(jsonObject)&&jsonObject.size()>0) {
//                            allocateApplyOrderDocumentLogDTO.setOperationType("编辑-更新货品明细");
//                            String remark = "更新了调拨预报单（" + featuresMap.get(CODE) + "）";
//                            s.add(remark);
//                            JSONArray addDetails = jsonObject.getJSONArray("addDetails");
//                            JSONArray deleteDetails = jsonObject.getJSONArray("deleteDetails");
//                            JSONArray closeDetails = jsonObject.getJSONArray("closeDetails");
//                            int num = 1;
//                            if (CollectionUtils.isNotEmpty(addDetails)) {
//                                for (int i = 0; i < addDetails.size(); i++) {
//                                    JSONObject object = addDetails.getJSONObject(i);
//                                    s.add("（" + num + "）添加货品行：" + object.getString("title") + "(" + object.getString("scItemId") + ")" + " " + object.getString("applyQuantity"));
//                                    num = num + 1;
//                                }
//                            }
//                            if (CollectionUtils.isNotEmpty(deleteDetails)) {
//                                for (int i = 0; i < deleteDetails.size(); i++) {
//                                    JSONObject object = addDetails.getJSONObject(i);
//                                    s.add("（" + num + "）删除货品行：" + object.getString("title") + "(" + object.getString("scItemId") + ")" + " " + object.getString("applyQuantity"));
//                                    num = num + 1;
//                                }
//                            }
//                            if (CollectionUtils.isNotEmpty(closeDetails)) {
//                                for (int i = 0; i < closeDetails.size(); i++) {
//                                    JSONObject object = addDetails.getJSONObject(i);
//                                    s.add("（" + num + "）关闭货品行：" + object.getString("title") + "(" + object.getString("scItemId") + ")" + " " + object.getString("applyQuantity"));
//                                    num = num + 1;
//                                }
//                            }
//                            allocateApplyOrderDocumentLogDTO.setOperationContent(s);
//                            allocateApplyOrderDocumentLogDTOS.add(allocateApplyOrderDocumentLogDTO);
//                        }
//                    }
//                }
            }
        }
        return Result.success(allocateApplyOrderDocumentLogDTOS);
    }

    @Override
    public Result<List<AllocateApplyOrderListDTO>> nykQueryAllocateApplyOrderList(AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest) {
        Result<List<AllocateApplyOrderListDTO>> listResult = new Result<>();
        List<AllocateApplyOrderListDTO> list = new ArrayList<>();
        listResult.setResult(list);
        listResult.setSuccess(true);
        String allocateApplyOrderRolesThatCanBeViewed = OtsUnifiedInventoryConstants.ALLOCATE_APPLY_ORDER_ROLES_THATCAN_BE_VIEWED();
        List<String> allocateApplyOrderRolesThatCanBeVieweds = Arrays.asList(allocateApplyOrderRolesThatCanBeViewed.split(COMMA));
        Map<String, String> allocateApplyOrderRolesThatCanBeViewedMap = new HashMap<>();
        for (String s : allocateApplyOrderRolesThatCanBeVieweds) {
            allocateApplyOrderRolesThatCanBeViewedMap.put(s, s);
        }
        return esAllocateApplyOrderIndexRepository.queryEsAllocateApplyOrderIndexList(allocateApplyOrderQueryRequest);
    }

    @Override
    public Result<String> getAllocateApplyOrderIdByOutAllocateApplyOrderId(GetAllocateApplyOrderIdByOutAllocateApplyOrderIdRequest request) {
        Result<String> result = new Result();
        if (StringUtils.isEmpty(request.getOutAllocateApplyOrderId())){
            result.setSuccess(false);
            return result;
        }
        return allocateApplyOrderReadRepository.getAllocateApplyOrderIdByOutAllocateApplyOrderId(request.getOutAllocateApplyOrderId());
    }

    /**
     * 当前登录人下拉 对业务员做一个特殊判断
     * @return
     */
    @Override
    public Result<List<AllocateOrganizationSelect>> getCurrentEmployeeOrganizationSelect() {
        List<AllocateOrganizationSelect> list = Lists.newArrayList();
        //获取到登录人了
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        OrganizationSDO organizationSDO = loginEmployeeInfo.getOrganizationSDO();
        if (organizationSDO == null){
            return Result.success(list);
        }
        List<RoleSDO> roles = loginEmployeeInfo.getRoles();
        if (CollectionUtils.isEmpty(roles)){
            return Result.success(list);
        }
        boolean isSalesMan = roles.stream().anyMatch(x -> SALES_MAN_ROLE_CODE.equals(x.getCode()));
        //如果是业务员
        if (isSalesMan){
            //循环找到对应的分子公司层级 type是103 根据父组织id寻找.
            while (!Objects.equals(103,organizationSDO.getType())){
                BaselineGetOrganizationById2Request request = new BaselineGetOrganizationById2Request();
                if (StringUtils.isBlank(organizationSDO.getParentId())){
                    return Result.success(list);
                }
                request.setId(organizationSDO.getParentId());
                Result<OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(request);
                if (organizationSDOResult == null || organizationSDOResult.getResult() == null){
                    return Result.success(list);
                }
                organizationSDO = organizationSDOResult.getResult();
                //如果组织层级大于103了 就不符合循环要求了.
                if (organizationSDO.getType() != null && organizationSDO.getType() <103){
                    return Result.success(list);
                }
            }

        }
        AllocateOrganizationSelect select = new AllocateOrganizationSelect();
        select.setLabel(organizationSDO.getName());
        select.setValue(organizationSDO.getId());
        list.add(select);
        return Result.success(list);

    }
}

